﻿using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace SunnyPaine.Autofac.Extension.SqlSugar.Context
{
    /// <summary>
    /// 数据库连接上下文。
    /// </summary>
    internal class DBAContext
    {
        private static readonly ThreadLocal<IDictionary<string, ISqlSugarClient>> ThreadLocal_Client =
            new ThreadLocal<IDictionary<string, ISqlSugarClient>>();


        public static void SetClient(IDictionary<string, ISqlSugarClient> clients)
        {
            ThreadLocal_Client.Value = clients;
        }

        public static IDictionary<string, ISqlSugarClient> GetClients()
        {
            return ThreadLocal_Client.Value;
        }

        public static ISqlSugarClient GetClient(string configId)
        {
            if (ThreadLocal_Client.Value == null)
            {
                return null;
            }
            if (string.IsNullOrEmpty(configId))
            {
                return ThreadLocal_Client.Value.Values.First();
            }
            if (ThreadLocal_Client.Value.ContainsKey(configId))
            {
                return ThreadLocal_Client.Value[configId];
            }
            return null;
        }

        public static void Clear()
        {
            ThreadLocal_Client.Value.Clear();
        }
    }
}
